<template>
  <TopNavBar :title="_t18('27_title')" type="back" />

  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <div class="recharge-apply-container" :key="reloadKey">
      <div class="qr-section">
        <img class="qr-img" :src="qrCodeUrl" alt="QR Code" />
      </div>

      <div class="form-section">
        <div class="form-item">
          <label class="form-label">{{ _t18('27_network') }}</label>
          <div class="form-value select-value network-select-trigger" @click="openNetworkSelect">
            {{ selectedNetwork }}
            <svg style="margin-left:auto;" width="18" height="18" viewBox="0 0 24 24">
              <path d="M7 10l5 5 5-5" stroke="#bbb" stroke-width="2" fill="none" />
            </svg>
          </div>
        </div>

        <div class="form-item">
          <label class="form-label">{{ _t18('27_coin') }}</label>
          <div class="form-value coin-value coin-select-trigger" @click="openCoinSelect">
            <img :src="coinOptions.find(c => c.value === selectedCoin)?.icon" class="coin-icon" alt="coin" />
            {{ selectedCoin }}
            <svg class="suffix-icon" width="12" height="12" viewBox="0 0 24 24">
              <path d="M8 5l8 7-8 7Z" fill="#999" />
            </svg>
          </div>
        </div>

        <div class="form-item">
          <label class="form-label">{{ _t18('27_address') }}</label>
          <div class="form-value address-value">
           
		     <span class="address-text">{{ address  }}</span>
            <button class="copy-btn" @click="copyAddress">
              <svg width="24" height="24" viewBox="0 0 24 24">
                <path
                  d="M14.9671 4.4985C15.4457 4.4985 15.8724 4.60219 16.2473 4.80957C16.6221 5.01695 16.9452 5.27218 17.2163 5.57527C17.4875 5.87836 17.6949 6.20538 17.8385 6.55633C17.982 6.90728 18.0538 7.21835 18.0538 7.48953V21.009C18.0538 21.4716 17.9621 21.8863 17.7787 22.2532C17.5952 22.6201 17.3559 22.9312 17.0608 23.1864C16.7657 23.4417 16.4347 23.6411 16.0678 23.7846C15.7009 23.9282 15.334 24 14.9671 24H3.17048C2.86739 24 2.53638 23.9123 2.17746 23.7368C1.81854 23.5613 1.48354 23.33 1.17247 23.0429C0.861407 22.7557 0.602185 22.4247 0.394807 22.0499C0.187429 21.675 0.0837402 21.2961 0.0837402 20.9133V7.58524C0.0837402 7.25025 0.163501 6.90329 0.323022 6.54437C0.482544 6.18544 0.689922 5.85444 0.945156 5.55135C1.20039 5.24826 1.4955 4.99701 1.8305 4.79761C2.1655 4.59821 2.51644 4.4985 2.88334 4.4985H14.9671ZM13.5553 19.4536C13.9701 19.4536 14.325 19.3101 14.6201 19.0229C14.9152 18.7358 15.0628 18.3848 15.0628 17.9701C15.0628 17.5553 14.9152 17.2004 14.6201 16.9053C14.325 16.6102 13.9701 16.4626 13.5553 16.4626H4.58225C4.16749 16.4626 3.81255 16.6102 3.51744 16.9053C3.22232 17.2004 3.07477 17.5553 3.07477 17.9701C3.07477 18.3848 3.22232 18.7358 3.51744 19.0229C3.81255 19.3101 4.16749 19.4536 4.58225 19.4536H13.5553ZM13.5553 13.4716C13.9701 13.4716 14.325 13.328 14.6201 13.0409C14.9152 12.7537 15.0628 12.4028 15.0628 11.988C15.0628 11.5733 14.9152 11.2183 14.6201 10.9232C14.325 10.6281 13.9701 10.4806 13.5553 10.4806H4.58225C4.16749 10.4806 3.81255 10.6281 3.51744 10.9232C3.22232 11.2183 3.07477 11.5733 3.07477 11.988C3.07477 12.4028 3.22232 12.7537 3.51744 13.0409C3.81255 13.328 4.16749 13.4716 4.58225 13.4716H13.5553ZM17.7906 0C18.4766 0 19.1067 0.20339 19.681 0.610169C20.2552 1.01695 20.7537 1.51944 21.1765 2.11765C21.5992 2.71585 21.9302 3.36191 22.1695 4.05583C22.4088 4.74975 22.5284 5.38385 22.5284 5.95813V18.664C22.5284 18.999 22.4287 19.3061 22.2293 19.5852C22.0299 19.8644 21.7866 20.1037 21.4995 20.3031C21.2124 20.5025 20.9013 20.662 20.5663 20.7817C20.2313 20.9013 19.9202 20.9611 19.6331 20.9611H19.5374V6.67597C19.4098 5.57527 19.0668 4.72981 18.5085 4.13958C17.9501 3.54935 17.2084 3.1665 16.2831 2.99103H4.60617C4.62213 2.95912 4.6301 2.90329 4.6301 2.82353C4.6301 2.50449 4.72581 2.17747 4.91724 1.84247C5.10867 1.50748 5.35991 1.20439 5.67098 0.9332C5.98205 0.662014 6.32901 0.438684 6.71186 0.26321C7.09471 0.0877368 7.47756 2.34375e-08 7.86041 2.34375e-08L17.7906 0Z"
                  fill="var(--text-color)"
                ></path>
              </svg>
            </button>
          </div>
        </div>

        <div class="form-item">
          <label class="form-label">{{ _t18('27_amount') }}</label>
          <input
            class="form-input"
            v-model="amount"
            :placeholder="_t18('27_inputPlaceholder')"
            type="number"
            min="0.0001"
            step="0.0001"
          />
        </div>

        <div class="form-item">
          <label class="form-label">{{ _t18('27_uploadVoucher') }}</label>
          <div class="upload-section">
            <div class="upload-box">
              <van-uploader :after-read="afterRead" max-count="1" v-model="fileList">
                <svg width="40" height="40" viewBox="0 0 24 24">
                  <path
                    fill="#f5a623"
                    d="M12 16v-8m0 0l-4 4m4-4l4 4M4 20h16"
                    stroke="#f5a623"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  />
                </svg>
              </van-uploader>
            </div>
          </div>
        </div>
      </div>

      <div class="pay-btn-section">
        <button class="pay-btn" @click="submit">{{ _t18('27_pay') }}</button>
      </div>
	  <p class="user-type-label">
  {{ _t18('27_user_type') }}: {{ userType }}
</p>
    </div>
  </van-pull-refresh>

  <!-- 网络选择弹窗 -->
  <transition name="fade">
    <div v-if="showNetworkSelect" class="network-select-modal">
      <div class="network-select-mask" @click="closeNetworkSelect"></div>
      <transition name="slide-up-bottom">
        <div v-if="showNetworkSelect" class="network-select-popup-bottom">
          <div class="network-select-header">
            <span>{{ _t18('27_selectNetwork') }}</span>
            <svg class="close-btn" @click="closeNetworkSelect" width="24" height="24" viewBox="0 0 24 24">
              <path d="M6 6l12 12M6 18L18 6" stroke="#888" stroke-width="2" stroke-linecap="round" />
            </svg>
          </div>
          <div class="network-select-list">
            <div v-for="item in networkOptions" :key="item.value" class="network-select-item" @click="selectNetwork(item.value)">
              <span>{{ item.label }}</span>
              <img :src="selectedNetwork === item.value ? currentIcon : noCuttemdIcon" class="network-check-icon" />
            </div>
          </div>
        </div>
      </transition>
    </div>
  </transition>

  <!-- 币种选择弹窗 -->
  <transition name="fade">
    <div v-if="showCoinSelect" class="network-select-modal">
      <div class="network-select-mask" @click="closeCoinSelect"></div>
      <transition name="slide-up-bottom">
        <div v-if="showCoinSelect" class="network-select-popup-bottom">
          <div class="network-select-header">
            <span>{{ _t18('27_selectCoin') }}</span>
            <svg class="close-btn" @click="closeCoinSelect" width="24" height="24" viewBox="0 0 24 24">
              <path d="M6 6l12 12M6 18L18 6" stroke="#888" stroke-width="2" stroke-linecap="round" />
            </svg>
          </div>
          <div class="network-select-list">
            <div v-for="item in coinOptions" :key="item.value" class="network-select-item" @click="selectCoin(item.value)">
              <div style="display:flex;align-items:center;gap:10px;">
                <img :src="item.icon" class="coin-icon" alt="coin" />
                <span>{{ item.label }}</span>
              </div>
              <img :src="selectedCoin === item.value ? currentIcon : noCuttemdIcon" class="network-check-icon" />
            </div>
          </div>
        </div>
      </transition>
    </div>
  </transition>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useMainStore } from '@/store'
import { useToast } from '@/hook/useToast'
import { _t18, _hideAddress, _toView } from '@/utils/public'
import { uploadImg } from '@/api/common/index.js'
import { rechargeSubmit } from '@/api/account.js'
import QRCode from 'qrcode'
import currentIcon from '@/assets/defi/current.png'
import noCuttemdIcon from '@/assets/defi/noCuttemd.png'
import { debounce } from 'lodash'
import { useRoute } from 'vue-router'

// ✅ 新增导入
import { useUserStore } from '@/store/user/index'

// ✅ 新增实例
const userStore = useUserStore()

// ✅ 计算属性获取用户类型
const userType = computed(() => userStore.userInfo?.user?.userType || 'normal')


const route = useRoute()
const { _toast } = useToast()
const mainStore = useMainStore()

const refreshing = ref(false)
const reloadKey = ref(Date.now())

// 刷新逻辑
const onRefresh = async () => {
  refreshing.value = true
  try {
    await mainStore.getSettingConfig()
    _toast('27_refresh_success')
    reloadKey.value = Date.now()
  } catch {
    _toast('27_refresh_fail')
  } finally {
    setTimeout(() => (refreshing.value = false), 600)
  }
}

onMounted(async () => {
  createQRImage(address.value)
  if (!userStore.userInfo?.user) {
    await userStore.getUserInfo?.() // 确认 userStore 内有这个方法
  }
  console.log('当前用户类型：', userType.value)
})

// ✅ 网络映射表
const networkMap = {
  usdt: [
    { label: 'TRC20', value: 'USDT-TRC' },
    { label: 'ERC20', value: 'USDT-ERC' }
  ],
  eth: [
    { label: 'ERC20', value: 'ETH-ERC' }
  ],
  usdc: [
    { label: 'ERC20', value: 'USDC-ERC' }
  ],
  btc: [
    { label: 'Bitcoin', value: 'Bitcoin' }
  ],
  base: [
    { label: 'ETH', value: 'BASE-ETH' },
    { label: 'USDT', value: 'BASE-USDT' },
    { label: 'USDC', value: 'BASE-USDC' }
  ],
  sol: [
    { label: 'SOL', value: 'SOL-SOLANA' }
  ]
}

// ✅ 币种选项
const coinOptions = [
  { label: 'USDT', value: 'usdt', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/1e8deac3f3e547629a8bf2b466dc0359.png' },
  { label: 'ETH', value: 'eth', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/ede2393ae55247b686b96c38231d4676.png' },
  { label: 'USDC', value: 'usdc', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/LOGOIPSUM/c0830db57f39487aa4a1205ff23c1633.png' },
  { label: 'BTC', value: 'btc', icon: 'https://s2.coinmarketcap.com/static/img/coins/64x64/1.png' },
  { label: 'BASE', value: 'base', icon: 'https://static-assets.coinbase.com/ui-infra/illustration/v1/pictogram/svg/light/coinbaseLogoNavigation-4.svg' },
  { label: 'SOL', value: 'sol', icon: '' }
]

// ✅ 初始化参数来自 URL
const selectedCoin = ref(route.query.coin?.toLowerCase() || 'usdt')
const networkOptions = ref(networkMap[selectedCoin.value])
const selectedNetwork = ref(route.query.type || networkOptions.value[0]?.value || '')

// ✅ 监听币种变化，自动切换链
watch(selectedCoin, (newVal) => {
  networkOptions.value = networkMap[newVal] || []
  selectedNetwork.value = networkOptions.value[0]?.value || ''
  createQRImage(address.value)
})

// ✅ 地址映射（示例）
const address = computed(() => {
  const key = (selectedNetwork.value || '').toLowerCase()
  const fixed = {
    'usdt-erc': '0xCe1e7A2C5A668168A72ab959B0bc66450ab2104f',
    'usdt-trc': 'TDqXnpNAuCmrWbG9FXGSSrf7jKTtP8FJuK',
    'base-eth': '0x1234BaseEthAddr998877',
    'base-usdt': '0x1234BaseUsdtAddr998877111',
    'base-usdc': '0x1234BaseUsdcAddr998877222',
    'bitcoin': 'bc1qexamplebtcaddress123456789',
	'sol-solana': 'bc1qexample33747733333',
	'eth-erc': 'X00000bc1qexample33747733333',
	'usdc-erc': 'X00000bc1qexample337477334443333888'
  }
  // 防止 undefined 报错
  return fixed[key] || fixed['usdt-trc']
})


// ✅ 隐藏地址展示
const maskedAddress = computed(() => _hideAddress(address.value))

const fileList = ref([])
const qrCodeUrl = ref('')
const amount = ref('')
const showNetworkSelect = ref(false)
const showCoinSelect = ref(false)

function openNetworkSelect() { showNetworkSelect.value = true }
function closeNetworkSelect() { showNetworkSelect.value = false }
function selectNetwork(val) {
  selectedNetwork.value = val
  closeNetworkSelect()
  createQRImage(address.value)
}

function openCoinSelect() { showCoinSelect.value = true }
function closeCoinSelect() { showCoinSelect.value = false }
function selectCoin(val) {
  selectedCoin.value = val
  showCoinSelect.value = false
}

// ✅ 上传逻辑
const afterRead = (file) => {
  file.status = 'uploading'
  const formData = new FormData()
  formData.append('file', file.file)
  uploadImg(formData).then((res) => {
    res = res.data
    if (res.code == '200') {
      file.res = res.data.url
      file.status = 'success'
    } else {
      _toast(res.msg)
      fileList.value = []
    }
  })
}

// ✅ 提交充值
// ✅ 提交充值
const submit = debounce(() => {
  // 检查用户类型
  if (userType.value === 1 || userType.value === '1') {
    return _toast('22_monimode_no_recharge')
  }

  if (!amount.value) return _toast('27_toast_amount')
  if (!fileList.value.length) return _toast('27_toast_upload')

  const file = fileList.value[0]
  if (file.status !== 'success') return _toast('27_toast_uploading')

  // ✅ 判断 base 网络对应币种
  let coinToSubmit = selectedCoin.value
  if (selectedCoin.value === 'base') {
    if (selectedNetwork.value === 'BASE-ETH') coinToSubmit = 'eth'
    else if (selectedNetwork.value === 'BASE-USDT') coinToSubmit = 'usdt'
    else if (selectedNetwork.value === 'BASE-USDC') coinToSubmit = 'usdt'
  }

  const params = {
    amount: amount.value,
    type: selectedNetwork.value,
    coin: coinToSubmit,
    filePath: file.res,
    address: address.value,
    userType: userType.value // 可选：传给后端方便记录
  }

  rechargeSubmit(params).then((res) => {
    if (res.code == '200') {
      _toast('27_success')
      amount.value = ''
      setTimeout(() => _toView('/assets'), 500)
    } else _toast(res.msg)
  })
}, 500)


// ✅ 生成二维码
const createQRImage = (addr) => {
  if (!addr) return
  QRCode.toDataURL(addr, { margin: 2, scale: 3, color: { dark: '#000', light: '#fff' } }).then((url) => (qrCodeUrl.value = url))
}

// ✅ 复制地址
function copyAddress() {
  navigator.clipboard.writeText(address.value)
  _toast('27_copySuccess')
}

// ✅ 初始化加载二维码
onMounted(() => {
  createQRImage(address.value)
})
</script>




<style scoped>
.recharge-apply-container {
  background: #f5f7fa;
  min-height: 100vh;
  padding: 0;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
}
.qr-section {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 32px 0 16px 0;
}
.qr-img {
  width: 200px;
  height: 200px;
  border-radius: 12px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.form-section {
  padding: 0 16px;
}
.form-item {
  margin-bottom: 18px;
}
.form-label {
  font-size: 16px;
  color: #222;
  font-weight: 600;
  margin-bottom: 6px;
  display: block;
}
.form-value {
  background: #fff;
  border-radius: 24px;
  padding: 12px 18px;
  font-size: 16px;
  color: #222;
  display: flex;
  align-items: center;
  min-height: 44px;
}
.select-value {
  justify-content: flex-start;
  cursor: pointer;
}
.coin-value {
  gap: 8px;
}
.coin-icon {
  width: 24px;
  height: 24px;
  margin-right: 6px;
}
.address-value {
  justify-content: space-between;
  gap: 8px;
}
.copy-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0 4px;
  display: flex;
  align-items: center;
}
.form-input {
  width: 100%;
  border: none;
  background: #fff;
  border-radius: 24px;
  padding: 12px 18px;
  font-size: 16px;
  color: #222;
  outline: none;
  min-height: 44px;
  box-sizing: border-box;
}
.upload-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.upload-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px dashed #f5a623;
  border-radius: 16px;
  background: #fff;
  padding: 24px 0 12px 0;
  cursor: pointer;
  transition: border 0.2s;
}
.upload-box:hover {
  border-color: #f90;
}
.upload-box svg {
  margin-bottom: 8px;
}
.upload-box span {
  color: #222;
  font-size: 15px;
  font-weight: 500;
}
.file-name {
  font-size: 14px;
  color: #888;
  margin-left: 8px;
}
.pay-btn-section {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 32px 0 24px 0;
  background: #f5f7fa;
  position: sticky;
  bottom: 0;
  z-index: 10;
}
.pay-btn {
  width: 90%;
  max-width: 460px;
  height: 60px;
  background: #000;
  color: #fff;
  border: none;
  border-radius: 999px;
  font-size: 16px;
  font-weight: 400;
  letter-spacing: 2px;
  cursor: pointer;
  transition: background 0.2s;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
}
.pay-btn:active {
  background: #222;
}
/* Network select modal styles */
.network-select-modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  z-index: 1000;
}
.network-select-mask {
  position: absolute;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0,0,0,0.08);
  z-index: 1;
}
.network-select-popup-bottom {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100vw;
  background: #f5f7fa;
  border-top-left-radius: 18px;
  border-top-right-radius: 18px;
  box-shadow: 0 -2px 24px rgba(0,0,0,0.08);
  z-index: 2;
  padding-bottom: 18px;
  padding-top: 8px;
  max-width: 100vw;
}
.network-select-header {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: 600;
  color: #222;
  padding: 18px 0 10px 0;
  position: relative;
}
.network-select-header .close-btn {
  position: absolute;
  right: 18px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
}
.network-select-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 0 0 0 0;
}
.network-select-item {
  background: #fff;
  border-radius: 999px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 18px;
  color: #222;
  padding: 14px 24px;
  margin: 0 18px;
  cursor: pointer;
  box-shadow: 0 1px 4px rgba(0,0,0,0.01);
  transition: background 0.15s;
}
.network-select-item:active {
  background: #f0f0f0;
}
.network-check-icon {
  width: 24px;
  height: 24px;
}
/* 动画样式 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.25s cubic-bezier(.4,0,.2,1);
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
.fade-enter-to, .fade-leave-from {
  opacity: 1;
}
.slide-up-bottom-enter-active, .slide-up-bottom-leave-active {
  transition: transform 0.28s cubic-bezier(.4,0,.2,1), opacity 0.28s cubic-bezier(.4,0,.2,1);
}
.slide-up-bottom-enter-from, .slide-up-bottom-leave-to {
  transform: translateY(100%);
  opacity: 0;
}
.slide-up-bottom-enter-to, .slide-up-bottom-leave-from {
  transform: translateY(0);
  opacity: 1;
}
.suffix-icon {
  margin-left: auto;
  display: block;
}
.address-text {
  font-size: 14px;       /* 字号 */
  font-weight: 500;      /* 字重 */
  color: #333;           /* 字体颜色 */
  word-break: break-all; /* 允许地址换行 */
  max-width: 80%;        /* 限制宽度 */
  line-height: 1.5;      /* 行高 */
}

/* 如果你希望单行显示+省略号，可改成以下 */
.address-text.single-line {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}


</style> 